const express = require('express')
const route = express.Router()
const path = require('path')

//引入校验中间件
const isLoginMiddle = require("../middleware/isLoginMiddle")
//引入数据库
const advModel = require("../db/model/advModel")
//引入 formData解析器
const formidable = require('formidable')


route.post('/addAdv',isLoginMiddle,async (req,res)=>{
  //配置form
  const form = formidable({
    //保存的地址
    uploadDir:path.resolve(__dirname,'../upload'),
    //是否保持原有后缀
    keepExtensions:true
  })
  form.parse(req,async (err,params,file)=>{
    const{
      advTitle,
      advType,
      advOrder
    }=params

   try{
    advModel.create({
      advTitle,
      advType,
      advOrder,
      advHref:'/upload/'+file.advPic.newFilename,
      addTime:new Date().toLocaleString()
    })
    res.send({
      code: 10000,
      msg: "添加广告成功",
      data: null
    })
   }catch(e){
    console.log("添加广告数据库操作出现异常" + e.message);
    return res.send({
          code: 10001,
          msg: "添加广告数据库操作出现异常" + e.message,
          data: null
    })
   }

  })

  


})
module.exports = route